﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Configuration;
using iSun.Entity;
using System.Runtime.InteropServices;
using System.Security.Permissions;

namespace UpLoadConsoleApplication
{

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]//　　注意： 类定义前需要加上下面两行，否则调用失败！
    [System.Runtime.InteropServices.ComVisibleAttribute(true)] 
    public partial class MainFrom : Form
    {
        public MainFrom()
        {
            InitializeComponent();
            webBrowser1.ObjectForScripting = new ScriptManager(this);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataAction.UploadSourceFile(0);
            MessageBox.Show("上传成功");
        }

        private void MainFrom_Load(object sender, EventArgs e)
        {
            this.webBrowser1.Url = new Uri(ConfigurationManager.AppSettings["step1URL"]);
            //this.webBrowser2.Url = new Uri(ConfigurationManager.AppSettings["step2URL"]);
            this.WindowState = FormWindowState.Maximized;

            if (ConfigurationManager.AppSettings["timeSpan"] != string.Empty)
            {
                timer1.Interval = Convert.ToInt32(ConfigurationManager.AppSettings["timeSpan"]);
            }
            timer1.Start();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string SN =  this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
            (new DialogForm(SN)).Show();
            //DataAction.DownLandFile();
            //MessageBox.Show("下载成功");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataAction.UploadSourceFile(1);
            MessageBox.Show("上传成功");
        }

        private void txtSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r' && txtSN.Text.Trim()!=string.Empty)
            {
                //MessageBox.Show(e.KeyChar.ToString());
                if (chkNewStatus.Checked)
                {
                    iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
                    iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
                    IList<ProductPhotoEnitty> list = new List<ProductPhotoEnitty>();
                    ProductPhotoEnitty pEntity = new ProductPhotoEnitty();
                    pEntity.SN = txtSN.Text;
                    pEntity.ProductName = txtSN.Text;
                    pEntity.ID = new Guid();
                    pEntity.AddTime = System.DateTime.Now;
                    pEntity.AddUser = Guid.Empty;
                    list.Add(pEntity);
                    channel.UploadProduct(ZX.Common.Globals.ListToJson<ProductPhotoEnitty>(list));
                    DataAction.CreateProductDir(txtSN.Text);
                }

                this.webBrowser1.Document.GetElementById("NewStatus").SetAttribute("value", this.chkNewStatus.Checked.ToString());

                this.webBrowser1.Document.GetElementById("SN").SetAttribute("value", txtSN.Text);
                webBrowser1.Document.InvokeScript("show");

      
                this.txtSN.Focus();
                this.txtSN.SelectAll();

                this.txtSN.Text = "";
            }
        }

        [ComVisible(true)]
        public class ScriptManager
        {
            MainFrom _form;
            public ScriptManager(MainFrom form)
            {
                _form = form;
            }
            public void ShowMessage(object obj)
            {
                MessageBox.Show(obj.ToString());
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                string SN = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
                if (SN != string.Empty)
                {
                    int flag = 0;
                    DataAction.MoveFile(SN,out flag);
                    if (flag == 1)
                    {
                        webBrowser1.Document.InvokeScript("fnRefresh");
                    }
                }
            }
            catch (Exception e1)
            {
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            (new iSun.App.frmEditConfig()).Show();
        }

        private void txtSN_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtSN_Enter(object sender, EventArgs e)
        {
            this.txtSN.SelectAll();
        }

        private void chkNewStatus_CheckedChanged(object sender, EventArgs e)
        {
            this.webBrowser1.Document.GetElementById("NewStatus").SetAttribute("value", this.chkNewStatus.Checked.ToString());
        }

        /// <summary>
        /// 删除相片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteProduct_Click(object sender, EventArgs e)
        {
            string SN = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");

            if (MessageBox.Show("是否删除" + SN + "?","确认", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                string sourceURL = ConfigurationManager.AppSettings["filePath"];
                try
                {
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(sourceURL + SN);
                    dir.Delete(true);
                }
                catch (Exception e1)
                {
                }

                try
                {
                    iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
                    iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
                    channel.DeleteProuct(SN);
                }
                catch (Exception e1)
                {
                }
                webBrowser1.Document.InvokeScript("DeleteNodes");
                MessageBox.Show("产品删除成功！");
            }
        }

        private void OpenFolder(string path)
        {
            if (System.IO.Directory.Exists(path))
            {
                System.Diagnostics.Process.Start("explorer.exe", path);
            }
            else
            {
                MessageBox.Show("没有相关文件夹！");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string o = webBrowser1.Document.InvokeScript("GetSelectedImages") as string;
            if (o == "")
            {
                return;
            }

            if (MessageBox.Show("是否删除选定的图片?", "确认", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                //string o = webBrowser1.Document.InvokeScript("GetSelectedImages") as string;
                DeleteImages(o);
                DataAction.DeleteImages(o);
                MessageBox.Show("产品图片删除成功！");
                webBrowser1.Document.InvokeScript("fnRefresh");
            }
        }

        private void DeleteImages(string images)
        {
            string[] imagePath = images.Split(',');
            //ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            foreach (string _image in imagePath)
            {
                string Path1= ConfigurationManager.AppSettings["filePath"];
                string Path2 = ConfigurationManager.AppSettings["filePath1"];
                string filePath = "";
                if (_image.ToLower().Contains("\\upload\\photo1"))
                {
                  filePath =  Path2+  _image.ToLower().Replace("\\upload\\photo1\\", "");
                }
                else
                {
                    filePath = Path1 + _image.ToLower().Replace("\\upload\\photo\\", "");
                }
                string _path = ZX.Common.FileHelper.GetFileDir(filePath);
                string _filename = ZX.Common.FileHelper.GetFileNameNoPath(filePath);

                string _filePath = _path + "\\uploaded_" + _filename;
                //webPath = webPath + _image;
                if (System.IO.File.Exists(_filePath))
                {
                    System.IO.File.Delete(_filePath);
                }
                //ZX.Common.FileHelper.GetFileDir(
                //bll.RunSqlCommand(string.Format("delete from gs_ProductImage where FilePath='{0}';", _image));
            }
        }
        
        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void btnSourceFolder_Click(object sender, EventArgs e)
        {
            string SN = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
            string[] _str = SN.Split('_');
        
           string sourcePath = ConfigurationManager.AppSettings["filePath"]+(SN.Length>36?_str[1]:SN);
           if (SN.Length > 36)
           {
               switch (_str[2])
               {
                   case "0":
                       sourcePath = sourcePath + "\\images\\";
                       //__ttype = "P";
                       break;
                   case "1":
                       sourcePath = sourcePath + "\\thumb\\";
                       //__ttype = "T";
                       break;
                   case "2":
                       sourcePath = sourcePath + "\\vedio\\";
                       //__ttype = "V";
                       break;
                   default:
                       sourcePath = sourcePath + "\\images\\";
                       //__ttype = "P";
                       break;
               }
           }
           OpenFolder(sourcePath);
        }

        private void btnModifyFolder_Click(object sender, EventArgs e)
        {
            string SN = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
            string[] _str = SN.Split('_');

            string sourcePath = ConfigurationManager.AppSettings["filePath1"] + (SN.Length > 36 ? _str[1] : SN);
            if (SN.Length > 36)
            {
                switch (_str[2])
                {
                    case "0":
                        sourcePath = sourcePath + "\\images\\";
                        //__ttype = "P";
                        break;
                    case "1":
                        sourcePath = sourcePath + "\\thumb\\";
                        //__ttype = "T";
                        break;
                    case "2":
                        sourcePath = sourcePath + "\\vedio\\";
                        //__ttype = "V";
                        break;
                    default:
                        sourcePath = sourcePath + "\\images\\";
                        //__ttype = "P";
                        break;
                }
            }
            OpenFolder(sourcePath);
        }
    }
}
